var ftp = require('ftp')
const fs = require('fs')
const path = require('path')



const Client = require('ftp')
var client = new Client();
var targetOptions = {
    host: "118.24.219.157",
    port: 21,
    user: "xxx",
    password: "xxx"
};
//Object.assign(targetOptions,)
targetOptions = require("./ftp.config").targetOptions
client.connect(targetOptions);
client.on('ready', function () {
    uploadDic(path.join(__dirname, "../../../dist"), "/80")
    client.end();
})

function uploadDic(local, target) {
    const arr = fs.readdirSync(local)
    var files = []
    var dirs = []

    const uploadChildren = function () {
        arr.forEach(item => {
            // 文件路径
            const itemPath = path.join(local, item)
            const isDir = fs.statSync(itemPath).isDirectory()
            if (isDir) {
                // 是目录 递归
                uploadDic(itemPath, path.join(target, item))
            } else {
                files.push(item)
            }
        })
        files.forEach(item => {
            client.put(path.join(local, item), path.join(target, item), function (err) {
                if (!err) {
                    console.log("文件上传成功" + path.join(target, item))
                } else {
                    console.log("ftp远程文件上传失败" + path.join(target, item) + err)
                }
            })
        })

    }
    client.get(target, function (err) {
        if (err) {
            console.log("ftp远程目录" + target + "获取失败" + err)
            // 目录不存在
            client.mkdir(target, true, function (err) {
                if (!err) {
                    console.log("成功创建远程目录" + target)
                }
                uploadChildren()
            })
        } else {
            uploadChildren()
        }
    })

}